package top.minishow.pdf.utils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Base64;

public class Base64Utils {
    /**
     * 将文件进行base64编码
     *
     * @param filePath 文件路径
     * @return 文件编码后的字符串
     */
    public static String encode(String filePath) throws Exception {
        FileInputStream inputStream = new FileInputStream(filePath);
        byte[] data = new byte[inputStream.available()];
        inputStream.read(data);
        return Base64.getEncoder().encodeToString(data);
    }

    /**
     * 将文件进行base64编码
     *
     * @param inputStream 文件流
     * @return 文件编码后的字符串
     */
    public static String encode(FileInputStream inputStream) throws Exception {
        byte[] data = new byte[inputStream.available()];
        inputStream.read(data);
        return Base64.getEncoder().encodeToString(data);
    }

    /**
     * 将文件base64编码转为文件
     *
     * @param base64   文件base64编码
     * @param filePath 文件要保存的路径
     */
    public static void decode(String base64, String filePath) throws Exception {
        byte[] data = Base64.getDecoder().decode(base64);
        FileOutputStream outputStream = new FileOutputStream(filePath);
        outputStream.write(data);
    }
}
